#include "my_hash_table.h"
#include "global_declarations.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#define BUFF_SIZE 100

typedef void (*commandPtr)(char* firstWord, HashTable* table);
void execute_clear(char* firstWord, HashTable* table);
void execute_get_name(char* firstWord, HashTable* table);
void execute_insert(char* words, HashTable* table);
void execute_quit(char* firstWord, HashTable* table);
commandPtr getCommand(char* first_word);



int main(void){
	char buff[100] = {0};
	char* firstWord;
	commandPtr command;
	HashTable* table = create_new_my_hash_table();

	while  (true) {
		fgets(buff, BUFF_SIZE, stdin);
		firstWord = strtok(buff, " \n\0");
		command = getCommand(firstWord);
		if (command == 0) {
			printf("invalid command.\n");
			execute_quit(firstWord, table);
		}
		command(firstWord, table);
		memset(buff, 0, 100);
	}
	return 0;
}

commandPtr getCommand(char* first_word) {
	if (strcmp(first_word, "INSERT") == 0)
		return execute_insert;

	if (strcmp(first_word, "QUIT") == 0)
			return execute_quit;

	if (strcmp(first_word, "CLEAR") == 0)
			return execute_clear;

	if (strcmp(first_word, "GETNAME") == 0)
			return execute_get_name;

	else
		return NULL;

}

void execute_quit(char* firstWord, HashTable* table){
	int i;
	clear_all_my_hash_table(table);
	for (i = 0; i < HASH_TABLE_SIZE; ++i) {
		free(table->buckets[i]);
	}
	free(table);
	free(get_allocator());
	exit(0);
}

void execute_insert(char* words, HashTable* table){
	unsigned int id;
	words = strtok(0, " \n");
	id = atoi(words);
	words = strtok(0, "\n");
	if (retrieve_record_my_hash_table(table, id) == 0){
	insert_record_my_hash_table(table, id, words);
	printf("Insertion succeeded.\n");
	}
	else {
		printf("%d is already in the database.\n", id);
	}
}

void execute_clear(char* firstWord, HashTable* table){
	clear_all_my_hash_table(table);
	firstWord = 0; /* just for compilation*/
}

void execute_get_name(char* firstWord, HashTable* table){
	char* id_str = strtok(0, " \n");
	unsigned int id_num = atoi(id_str);
	Record* rec = (retrieve_record_my_hash_table(table, id_num));
	if (rec == 0){
		printf("%d is not in the database.\n", id_num);
		return;
	}
	else {
		printf("%s\n", rec->name);
	}
}
